package com.itheima.controller;


import com.itheima.common.R;
import lombok.extern.slf4j.Slf4j;
import org.apache.tomcat.util.http.fileupload.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.UUID;

@Slf4j
@RestController
@RequestMapping("/common")
//文件上传和下载
public class CommonController {

    @Value("${reggie.filepath}")
    private String path;

    @PostMapping("/upload")
    public R<String> upload(MultipartFile file) {
        //拿到文件名
        String filNname = UUID.randomUUID().toString();
        //截取
        String originalFilename = file.getOriginalFilename();
        //拿取文件后缀名 .后面的（如： .jpg）
        String substring = originalFilename.substring(originalFilename.lastIndexOf("."));
        //看看文件是否存在，如果不存在则自动创建文件
        File file1 = new File(path);
        if (!file1.exists()) {
            file1.mkdirs();
        }

        //将文件存储到指定的位置
        try {
            file.transferTo(new File(path, filNname + substring));
        } catch (IOException e) {
            e.printStackTrace();
            return R.error("出错了，请稍后重试！！！");
        }
        //返回文件名
        return R.success(filNname + substring);
    }

    @GetMapping("/download")
    //图片（文件）下载
    public void download(String name, HttpServletResponse response) {
        //用字节流写

        try {
            response.setContentType("image/jpeg");
            FileInputStream fileInputStream = new FileInputStream( new File(path ,name));
            ServletOutputStream outputStream = response.getOutputStream();
            IOUtils.copy(fileInputStream, outputStream);
            fileInputStream.close();
        } catch (Exception e) {
            e.printStackTrace();
        }


    }


}
